using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using MyHunter.Details;
using MyHunter.Interfaces;

using WeifenLuo.WinFormsUI.Docking;

using HunterPluginSDK;
using HunterPluginSDK.Interface;

namespace MyHunter
{
    public enum EditMode{New, Edit}
    delegate void UpdateUI();

    public partial class HunterForm : Form, 
        IProgressHandler,
        Interfaces.ICollectionManager
    {
        #region MEMBERS
        private List<MyHunter.Interfaces.ICollection> CollectionList;
        private Details.Collection collectionCtrl
        {
            get {
                return (Details.Collection)this.dockPanel.ActiveDocument;
            }
        }
        #region CONTENTS
        private Contents.CollectionsExplorer Explorer;
        private Contents.Output Output;
        #endregion
        #endregion

        #region CTOR
        public HunterForm()
        {
            InitializeComponent();
            InitializeContents();
        }

        private void InitializeContents()
        {
            Explorer = new Contents.CollectionsExplorer(this);
            Output = new Contents.Output();
            CollectionList = new List<ICollection>();
            dockPanel.ContentRemoved +=new EventHandler<DockContentEventArgs>(dockPanel_ContentRemoved);

            if(DataSchema.Settings.SettingsMgr.ShowCollectionExplorer)
                this.Explorer.Show(this.dockPanel, DockState.DockLeftAutoHide);
            if(DataSchema.Settings.SettingsMgr.ShowOutput)
                this.Output.Show(this.dockPanel, DockState.DockBottomAutoHide);
        }


        #endregion

        #region MENU

        #region COLLECTION
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateNewCollection();
        }


        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog.InitialDirectory = DataSchema.Settings.SettingsMgr.DefaultCollectionsPath;
            if (this.openFileDialog.ShowDialog() == DialogResult.OK)
            {
                OpenCollection(openFileDialog.FileName);
            }

        }


        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.SaveCollections();
        }

        private void closeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void addRemoveEntityToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            this.collectionCtrl.ManageEntity();
            Cursor = Cursors.Default;
        }
        #endregion

        #region TOOLS
        private void findToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tools.Find f = new Tools.Find(this);
            f.GoToShotEvent += new MyHunter.Tools.GoToShot(f_GoToShotEvent);
            f.Show();
        }

        void f_GoToShotEvent(DataSchema.CollectionSchema.ShotRow sr)
        {
            foreach(ICollection c in this.CollectionList)
            {
                if(c.Goto2Shot(sr) == true)
                    return;
            }
            HunterForm.ShowMsg("Can't navigate to desired item", MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }

        private void downloadNewCSVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Engine.Factory.CSVDonloader.GetCSV();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
             Engine.Factory.CSVDonloader.GetCSV();
        }
        private void backUpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.BackUp();
        }
        private void toolStripButtonBackUp_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.BackUp();
        }

        #endregion

        #region MANAGE

        private void huntToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.Hunt(Engine.CSV.ProcessType.Hunt);
        }

        private void toolStripButtonHuntNew_Click(object sender, EventArgs e)
        {
            Engine.Components.Interface.IHunter ih = Engine.Components.Hunter.CreateInstance(this, this.collectionCtrl.Coll);
            ih.Hunt();
        }

        private void verifyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.Hunt(Engine.CSV.ProcessType.Verify);
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.Stop();
        }

        private void burnToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.Burn();
        }

        private void updateCSVFilesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            this.collectionCtrl.UpdateCSV();
            Cursor = Cursors.Default;
        }



        private void toolStripButtonStop_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.Stop();
        }

        #endregion

        #region REPORT
        private void neededReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void lastHuntReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.CreateLastHuntReport();
        }

        private void generateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            this.collectionCtrl.CreateNeededReport();
            Cursor.Current = Cursors.Default;
        }

        private void openFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.collectionCtrl.OpenNeededReport();
        }

        #endregion

        #region VIEW
        private void collectionsExlorerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Explorer.Show(this.dockPanel, DockState.DockLeftAutoHide);
        }

        private void outputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Output.Show(this.dockPanel, DockState.DockBottomAutoHide);

        }

        #endregion

        #region HELP
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.ShowDialog();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UI.Settings set = new UI.Settings();
            if(set.ShowDialog() == DialogResult.OK)
            {
                DataSchema.Settings.SettingsMgr.SaveMyCollection();
            }
        }

        #endregion




        private void UpdateMenuToolbarSate()
        {
            if(this.CollectionList.Count > 0)
            {
                this.manageToolStripMenuItem.Enabled = true;
                this.toolsToolStripMenuItem.Enabled = true;
                this.reportToolStripMenuItem.Enabled = true;
                this.saveToolStripMenuItem.Enabled = true;
                this.toolStripButtonVerify.Enabled = true;
                this.toolStripButtonHunt.Enabled = true;
                this.toolStripButtonSave.Enabled = true;
                this.toolStripButtonBackUp.Enabled = true;
                this.toolStripButtonStop.Enabled = true;
            }
            else
            {
                this.manageToolStripMenuItem.Enabled = false;
                this.toolsToolStripMenuItem.Enabled = false;
                this.reportToolStripMenuItem.Enabled = false;
                this.saveToolStripMenuItem.Enabled = false;
                this.toolStripButtonVerify.Enabled = false;
                this.toolStripButtonHunt.Enabled = false;
                this.toolStripButtonSave.Enabled = false;
                this.toolStripButtonBackUp.Enabled = false;
                this.toolStripButtonStop.Enabled = false;
            }
        }




        #endregion

        #region ICollectionManager
        public void CreateNewCollection()
        {
            
            New.NewCollection nc = new New.NewCollection();
            if (nc.ShowDialog() == DialogResult.OK)
            {
                Details.Collection collCtrl = null;
                collCtrl = new Details.Collection(this, nc);
                SetUpContent(collCtrl);
            }
        }

        public bool ShowCollection(string name)
        {
            foreach(IDockContent c in this.dockPanel.Documents)
            {
                if(c is ICollection && ((ICollection)c).CollectionName == name)
                {
                    //dockPanel. = c;
                    return true;
                }
            }
            return false;
        }

        public void OpenCollection(string path)
        {
            Cursor = Cursors.WaitCursor;
            Details.Collection collCtrl = null;
            try
            {
                if(Engine.IO.FileTools.FileExist(path) == false)
                {
                    Cursor = Cursors.Default;
                    throw new Engine.Exceptions.CollectionNotFoundException(path);
                }
           
                collCtrl = new Details.Collection(this, path);
                SetUpContent(collCtrl);
            }
            catch(Engine.Exceptions.CollectionNotFoundException)
            {
                throw;
            }
            catch(Exception exep)
            {
                this.WriteToOutput(exep.ToString(), LogPriority.CRITICAL);
                /*foreach (DataTable dt in collCtrl.Coll.Tables)
                {
                    if (dt.HasErrors)
                    {
                        this.WriteToOutput("Problem with table " + dt.TableName, LogPriority.ERROR);
                    }
                }*/
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        public void SaveCollections()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                foreach (ICollection c in this.CollectionList)
                {
                    c.SaveCollection();
                    Explorer.UpdateMyCollection(c);
                }
                DataSchema.Settings.SettingsMgr.SaveMyCollection();
            }
            catch (Exception exep)
            {
                this.WriteToOutput(exep.ToString(), LogPriority.CRITICAL);
            }
            finally
            {
                Cursor = Cursors.Default;         
            }
        }

        public DataSchema.CollectionSchema.ShotRow[] FindShot(string sql, SearchIn si, List<string> fi, bool link)
        {
            List<DataSchema.CollectionSchema.ShotRow> srs = 
                new List<DataSchema.CollectionSchema.ShotRow>();

            if(si == SearchIn.Current)
            {
                srs.AddRange(this.collectionCtrl.FindShot(sql, fi, link));
            }
            else if(si == SearchIn.Loaded)
            {
                
                foreach(ICollection c in this.CollectionList)
                {
                    srs.AddRange(c.FindShot(sql, fi, link));
                }
            }
            else if(si == SearchIn.MyCollections)
            {

            }
            return srs.ToArray();
        }

        #endregion

        #region IProgressHandler

        public void LogException(Exception ex)
        {
            this.Output.WriteToOutput(ex.ToString());
        }


        public int TotalProgress
        {
            set
            {
                UpdateUI ui = delegate()
                {
                toolStripProgressBar.Value = 0;
                toolStripProgressBar.Maximum = value;
                };
                if (InvokeRequired)
                    this.Invoke(ui);
                else
                    ui();
            }
        }
        public void ProgressChanged()
        {
            UpdateUI ui = delegate()
            {
                if(toolStripProgressBar.Value < toolStripProgressBar.Maximum)
                    toolStripProgressBar.Value++;
            };

            if (InvokeRequired)
                this.Invoke(ui);
            else
                ui();
        }
        public string ProgressDesription
        {
            set
            {
                UpdateUI ui = delegate()
                {
                    this.toolStripHuntingStatusLabel.Text = value;
                    //WriteToOutput("\r\n", Engine.Business.Interfaces.LogPriority.INFO);
                    WriteToOutput(value, LogPriority.INFO);
                };
                if (InvokeRequired)
                    this.Invoke(ui);
                else
                    ui();
            }
        }
        /// <summary>
        /// Function Writes the text to output window
        /// </summary>
        /// <param name="txt">Text to log</param>
        /// <param name="prior">Log priority</param>
        public void WriteToOutput(string txt, LogPriority prior)
        {
            if((int)prior >= DataSchema.Settings.SettingsMgr.LogPriority)
            {
                UpdateUI ui = delegate()
                {
                    /*
                    string wto = DataSchema.Settings.SettingsMgr.WriteToOutput;
                    if(wto != ""
                        && txt.Contains(wto) == false 
                        && (int)prior <= (int)LogPriority.ACTIONHISTORY)
                        return;//we don't want to see it
                     */

                    int spacescount = (int)(LogPriority.CRITICAL) - (int)prior;
                    while(spacescount-- > 0)
                        txt = "  " + txt;
                    this.Output.WriteToOutput(txt);

                    if(prior == LogPriority.CRITICAL)
                        HunterForm.ShowMsg("Critical error. See output window for more details", MessageBoxButtons.OK, MessageBoxIcon.Error);

                };
                if (InvokeRequired)
                    this.Invoke(ui);
                else
                    ui();
            }
        }

        public string WatcherDescription
        {
            set
            {
                this.toolStripStatusLabelWatcher.Text = value;
                this.toolStripStatusLabelWatcher.ForeColor = Color.Green;
            }
        }

        public void WatcherChanged()
        {
//            this.toolStripStatusLabelIcon.Image = global::MyHunter.Properties.Resources.F036;
  //          Timer t = new Timer();
    //        t.Interval = 100;
      //      t.Tick += new EventHandler(t_Tick);
        }

        void t_Tick(object sender, EventArgs e)
        {
        //    this.toolStripStatusLabelIcon.Image = null;
        }

        #endregion

        #region PRIVATE
        private void SetUpContent(Collection cont)
        {

                if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
                {
                    cont.MdiParent = this;
                    cont.Show();
                }
                else
                     cont.Show(dockPanel);

            CollectionList.Add(cont);
            UpdateMenuToolbarSate();
        }
        #endregion

        #region EVENTS
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
        }
        void dockPanel_ContentRemoved(object sender, DockContentEventArgs e)
        {
            if(e.Content is ICollection)
            {
                this.CollectionList.Remove((ICollection)e.Content);
                UpdateMenuToolbarSate();
            }
        }

        #endregion

        #region static
        static public DialogResult ShowMsg(string txt, MessageBoxButtons mb, MessageBoxIcon ic)
        {
            return MessageBox.Show(txt, "Shark's Hunter", mb, ic);
        }
        #endregion

    }
}